package cn.jekun.shop.web.service;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpProductHis;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.shop.common.service.ShopBaseService;
import cn.jekun.shop.web.bean.HistoryGoods;
/**
 * 浏览过的商品
 * @author twj
 *
 */
@Service(HistoryService.BEAN_NAME)
public class HistoryService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.web.service.HistoryService";
	@Override
	public String getNamespace() {
		return "SHOP_PRODUCT_HISTORY";
	}
	/**
	 * 查询浏览过的商品
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONObject query(@RsUser.AnnoUserId String userId) {
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		 List resultList = new ArrayList();
		 Map formMap = new HashMap();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		formMap.put(ErpProductHis.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpProductHis.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.orderBy("a."+ErpProductHis.COL_CREATE_TIME+" desc nulls last"));
		resultList = this.list(formMap, page);
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(resultList, jsonConfig);
		jsonObject.put("goodsList", jsonArray);
		jsonObject.put("totals", page.getTotalCount());
		return executeRerutn(jsonObject);
	}
	/**
	 * 根据cookie，获取商品信息
	 * @param val
	 * @return
	 */
	public JSONObject queryHis(@Security()String val) {
		JSONObject jsonObject = new JSONObject();
		try {
			if (StringUtils.isBlank(val)) {
				return this.executeRerutnFail(jsonObject);
			}
			if ("null".equalsIgnoreCase(val)) {
				return this.executeRerutnFail(jsonObject);
			}
			String[] arr = val.split(";");
			if (arr==null || arr.length==0) {
				return this.executeRerutnFail(jsonObject);
			}
			String sql = "";
			for (int i = 0; i < arr.length; i++) {
				if (StringUtils.isBlank(arr[i])) {
					continue;
				}
				if ("null".equalsIgnoreCase(arr[i])) {
					continue;
				}
				String[] smArr = arr[i].split(",");
				if(smArr == null || smArr.length !=2 || StringUtils.isBlank(smArr[0])|| StringUtils.isBlank(smArr[1])){
					continue;
				}
				
				String shopId=smArr[0];
				String merchandiseId=smArr[1];
				if(sql.length()>0){
					sql+=" or ";
				}
				sql += "(a.shop_id='"+shopId+"' and b.merchandise_id='"+merchandiseId+"')";
				
			}
			if (sql.length()==0) {
				return this.executeRerutnFail(jsonObject);
			}
			Map map = new HashMap();
			map.put(SqlUtis.WHERE_SQL, sql);
			List<HistoryGoods> goods = this.list(this.getStatementName("listHis"), map);
			//排序
			List<HistoryGoods> sortGoods = new ArrayList<HistoryGoods>();
			for (int i = 0; i < arr.length; i++) {
				if (StringUtils.isBlank(arr[i])) {
					continue;
				}
				String[] smArr = arr[i].split(",");
				if(smArr == null || smArr.length !=2 || StringUtils.isBlank(smArr[0])|| StringUtils.isBlank(smArr[1])){
					continue;
				}
				String shopId=smArr[0];
				String merchandiseId=smArr[1];
				
				for (int j = 0; j < goods.size(); j++) {
					HistoryGoods historyGoods = goods.get(j);
					if (shopId.equals(historyGoods.getShopId()) && merchandiseId.equals(historyGoods.getMerchandiseId())) {
						sortGoods.add(historyGoods);
					}
				}
			}
			jsonObject.put("goods",sortGoods);
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
}
